import store from './stores/index.js';
import {
	RouterMount,
	createRouter,
	runtimeQuit
} from 'uni-simple-router';

const isLogin = function() {
	// const token = uni.getStorageSync('token')
	return true
}

const loginToPage = async function(to, from, next) {
	const status = isLogin();
	if (status) { // 已经登录
		next({
			name: 'index',
			NAVTYPE: 'replaceAll'
		});
	} else { //未登录 直接放行到登录页面
		if (to.name != 'login') {
			next({
				name: 'login',
				NAVTYPE: 'replace'
			});
		} else {
			next();
		}
	}
}

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	APP: {
		loadingPageHook: (view) => {
			view.hide()
		}
	},
	applet: {
		animationDuration: 300
	},
	routerBeforeEach: (to, from, next) => {
		const islogin = isLogin()
		if (islogin && to.name === 'login') {
			next({
				name: 'index',
				NAVTYPE: 'replaceAll'
			});
		} else {
			next();
		}


	},
	routerAfterEach: (to, from) => {},
	routerErrorEach: ({
		type,
		msg
	}) => {
		if (type !== 2) {
			router.$lockStatus = false;
		}
		// #ifdef APP-PLUS
		if (type === 3) {
			runtimeQuit();
		}
		// #endif
	},
	debugger: true,
	routes: [
		...ROUTES,
	]
});


let count = 0;
router.beforeEach((to, from, next) => {
	count++
	
	if (to.meta.auth) {
		if (count == 1) {
			loginToPage(to, from, next);
		} else {
			const status = isLogin();
			if (status) {
				next()
			} else {
				if (to.name != 'login') {
					next({
						name: 'login',
						NAVTYPE: 'replace'
					});
				}
			}
		}
	} else {
		const islogin = isLogin();
		if (count == 1) {
			loginToPage(to, from, next);
		} else {
			next();
		}
	}

});
router.afterEach((to, from, next) => {});

export {
	router,
	RouterMount
}
